package stormdemo;

import java.util.HashMap;
import java.util.Map;

import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;

public class WorldCountBolt extends BaseRichBolt {
	private static final long serialVersionUID = -6513172872853940438L;
	OutputCollector collector;
	Map<String,Long> wcMap = null;
	
	@Override
	public void prepare(@SuppressWarnings("rawtypes") Map stormConf, TopologyContext context, OutputCollector collector) {
		this.collector = collector;
		this.wcMap = new HashMap<>();
	}

	@Override
	public void execute(Tuple input) {
		String world = input.getStringByField("world");
		Long count = wcMap.get(world);
		if(count == null) {
			count = 0L;
		}
		count++;
		wcMap.put(world, count);
		collector.emit(new Values(world,count));
	}

	@Override
	public void declareOutputFields(OutputFieldsDeclarer declarer) {
		declarer.declare(new Fields("world", "count"));
	}

}
